package IC;

public class RunParameters 
{
	private final String _usage = "Usage: Compiler filepath [-print-ast] [-L<path/to/libic.sig>] [-dump-symtable] [-print-lir] [-opt-lir]";
	private final int _posibleArguments = 6;
	private boolean _printAST = false, _printSymTable = false, _printLir = false, _optLir = false;
	private String _libPath, _filePath, _errorMessage;
	
	public boolean IsPrintAST() { return _printAST; }
	public boolean IsPrintSymTable() { return _printSymTable; }
	public boolean IsPrintLir() { return _printLir; }
	public boolean IsOptLir() { return _optLir; }
	public String GetLibPath() { return _libPath; }
	public String GetFilePath() { return _filePath; }
	public boolean IsError() { return _errorMessage != null; }
	public String ErrorMessage() { return _errorMessage; }
	
	public RunParameters(String args[])
	{
		if (!CheckNumOfArgs(args))
			return;

		for (String arg : args)
			if (!ParseArg(arg))
				return;
		
		if (_filePath == null)
		{
			Error("No argument passed as file name.");
			return;
		}
	}
	
	private boolean CheckNumOfArgs(String args[])
	{
		if (args.length == 0)
		{
			Error("Not enough arguments.");
			return false;
		}
		else if (args.length > _posibleArguments)
		{
			Error("Too many arguments.");
			return false;
		}
		
		return true;
	}
	
	private void Error(String message)
	{
		_errorMessage = String.format("%s %s", message, _usage);
	}
	
	private boolean ParseArg(String arg)
	{
		if (RaiseFlags(arg))
			return true;
		
		if (arg.startsWith("-L"))
		{
			if (_libPath == null)
			{
				_libPath = arg.substring(2, arg.length());
				return true;
			}
			else
			{
				Error("Can't specify two librarys.");
				return false;
			}  			
		}
		
		if(_filePath == null)
		{
			_filePath = arg;
			return true;
		}
		
		Error("Unkown argument " + arg);
		return false;
	}
	
	private boolean RaiseFlags(String flagName)
	{
		if (flagName.equals("-print-ast"))
			return _printAST = true;
		
		else if (flagName.equals("-dump-symtab"))
			return _printSymTable = true;
		
		else if (flagName.equals("-print-lir"))
			return _printLir = true;
		
		else if (flagName.equals("-opt-lir"))
			return _optLir = true;
		
		return false;
	}
}
